/**
 * Created by xiewl on 2016/5/10.
 */
var urlParamObj = $$.util.urlParamToObj();
//计算form-box的高度
var calcFormHeight = function () {
    var clientHeight = document.body.clientHeight;
    var formEle = $('.form-box').get(0);
    var headerHeight = formEle.offsetTop + formEle.offsetParent.offsetTop;
    $('.form-box').css('height',clientHeight - headerHeight - 5);
};
//输入项调整排序
var adjustSort = function () {
    var $tbody = $('.form-form tbody'); 
    $tbody.sortable({
        axis:'y',
        containment:'.table',
        handle:'.move-icon'
    });
};
//输入项操作
var inputOperate = function () {
    //删除
    $('table').on('click','.delete',function () {
        var that = $(this);
        $$.modal.confirm('确认删除吗？','取消','确认',function () {
            that.parents('tr').remove();
        });
    });
    //编辑输入项
    $('table').on('click','.edit',function () {
        var json = JSON.parse(decodeURI($(this).parents('tr').attr('data-json')));
        var inputType = $(this).attr('data-type');
        var modalEle = $('#' + inputType);
        modalEle.modal('show').attr('data-index',$(this).parents('tr').index());
        modalEle.on('hidden.bs.modal',function (e) {
            modalEle.removeAttr('data-index');
        });
        modalEle.find('.input-title').val(json.name);
        if(inputType == 'inputMultiselect'){  //多选
            var html='';
           for(var i=0,len=json.options.length;i<len;i++){
                html+=[
                    '<div class="form-group row">',
                        '<label  class="col-md-2 col-xs-2 control-label text-right">选项</label>',
                        '<div class="col-md-5 col-xs-5 md-input">',
                        '<input type="text" class="form-control" value="'+ json.options[i].optionname +'"/>',
                        '</div>',
                        '<div class="col-md-5 col-xs-5 text-describe" >',
                        '候选选项 <span class="delete-node">删除该项</span>',
                        '</div>',
                    '</div>'
                ].join('');
            }
            $('#MultiselectMenu').html(html);
        }else if(inputType == 'inputRadio'){ //单选
            var html='';
            for(var i=0,len=json.options.length;i<len;i++){
                html+=[
                    '<div class="form-group row">',
                    '<label  class="col-md-2 col-xs-2 control-label text-right">选项</label>',
                    '<div class="col-md-5 col-xs-5 md-input">',
                    '<input type="text" class="form-control" value="'+ json.options[i].optionname +'"/>',
                    '</div>',
                    '<div class="col-md-5 col-xs-5 text-describe" >',
                    '候选选项 <span class="delete-node">删除该项</span>',
                    '</div>',
                    '</div>'
                ].join('');
            }
            $('#radioMenu').html(html);
        }else if(inputType == 'inputDropdown'){ //下拉
            var html='';
            for(var i=0,len=json.options.length;i<len;i++){
                html+=[
                    '<div class="form-group row">',
                    '<label  class="col-md-2 col-xs-2 control-label text-right">选项</label>',
                    '<div class="col-md-5 col-xs-5 md-input">',
                    '<input type="text" class="form-control" value="'+ json.options[i].optionname +'"/>',
                    '</div>',
                    '<div class="col-md-5 col-xs-5 text-describe" >',
                    '候选选项 <span class="delete-node">删除该项</span>',
                    '</div>',
                    '</div>'
                ].join('');
            }
            $('#dropMenu').html(html);
        }else if(inputType == 'inputValue'){   //数值
            $('#numUnit').val(json.unit);
            $('#numToggle').removeProp('checked');
            $('.max-min').hide();
            if(json.restriction){
                $('#numToggle').click();
                $('#numMax').val(json.restriction.max);
                $('#numMin').val(json.restriction.min);
            }
        }else if(inputType == 'inputSlider'){
            var html='';
            for(var i=0,len=json.options.length;i<len;i++){
                html+=[
                    '<div class="form-group row">',
                    '<label  class="col-md-2 col-xs-2 control-label text-right">选项</label>',
                    '<div class="col-md-5 col-xs-5 md-input">',
                    '<input type="text" class="form-control" value="'+ json.options[i].optionname +'"/>',
                    '</div>',
                    '<div class="col-md-5 col-xs-5 text-describe" >',
                    '候选选项 <span class="delete-node">删除该项</span>',
                    '</div>',
                    '</div>'
                ].join('');
            }
            $('#sliderMenu').html(html);
            $('#calcTotal').removeProp('checked');
            $('#calcAverage').removeProp('checked');
            if(json.alias == 1){
                $('#calcTotal').click();
            }else if(json.alias == 2){
                $('#calcAverage').click();
            }else if(json.alias == 3){
                $('#calcTotal').click();
                $('#calcAverage').click();
            }
            if(json.restriction){
                $('#sliderMin').val(json.restriction.min);
                $('#sliderMax').val(json.restriction.max);
            }
        }
    })
};
//新增输入项弹窗=====
var addInput=function(){
    //新增输入项
    $('.modal-input .modal-footer .btn-info').click(function () {
        var inputTitle = $(this).parents('.modal-input').find('.input-title').val();
        var json = {
            inputtype : $(this).attr('data-input-type'),
            type : $(this).attr('data-type'),
            name : inputTitle,
            id : Number($(this).attr('data-input-type') + $(this).attr('data-type') + $$.util.timeStamp())
        };
        if(json.inputtype == 3 && json.type == 1){  //保存下拉菜单
            var optionEle = $('#dropMenu .row');
            var optionArray = [];
            for(var i=0,len=optionEle.length;i<len;i++){
                optionArray.push({
                    optionid : i,
                    optionname : $(optionEle[i]).find('input[type="text"]').val()
                });
            }
            json.options = optionArray;
        }else if(json.inputtype == 1 && json.type == 0){ //保存数值型
            json.unit = $('#numUnit').val();
            //保存最值
            if($('#numToggle').is(':checked')){
                json.restriction = {
                    min : $('#numMin').val(),
                    max : $('#numMax').val()
                };
            }
        }else if(json.inputtype == 3 && json.type == 0){ //保存单选
            var optionEle = $('#radioMenu .row');
            var optionArray = [];
            for(var i=0,len=optionEle.length;i<len;i++){
                optionArray.push({
                    optionid : i,
                    optionname : $(optionEle[i]).find('input[type="text"]').val()
                });
            }
            json.options = optionArray;
        }else if(json.inputtype == 4 && json.type == 0){ //保存多选
            var optionEle = $('#MultiselectMenu .row');
            var optionArray = [];
            for(var i=0,len=optionEle.length;i<len;i++){
                optionArray.push({
                    optionid : i,
                    optionname : $(optionEle[i]).find('input[type="text"]').val()
                });
            }
            json.options = optionArray;
        }else if(json.inputtype == 8 && json.type == 0){ //保存滑块
            //保存选项
            var optionEle = $('#sliderMenu .row');
            var optionArray = [];
            for(var i=0,len=optionEle.length;i<len;i++){
                optionArray.push({
                    optionname : $(optionEle[i]).find('input[type="text"]').val()
                });
            }
            json.options = optionArray;
            //保存最值
            json.restriction = {
                min : $('#sliderMin').val(),
                max : $('#sliderMax').val()
            };
            //保存汇总方式（0：不选;1：求和;2：平均;3：全选）
            if(!$('#calcTotal').is(':checked') && !$('#calcAverage').is(':checked')){
                json.alias = 0;
            }else if($('#calcTotal').is(':checked') && !$('#calcAverage').is(':checked')){
                json.alias = 1;
            }else if(!$('#calcTotal').is(':checked') && $('#calcAverage').is(':checked')){
                json.alias = 2;
            }else{
                json.alias = 3;
            }
        };
        var replaceIndex = $(this).parents('.modal-input').attr('data-index');
        createInputItem(json,+replaceIndex);
        $('.modal-input').modal('hide').removeAttr('data-index');
    });
    $('#nextStep').click(function(){
        var type = $('.popuptable input:checked').attr('data-type');
        $('#addInput').modal('hide');
        $('#'+ type).find('input').val('').removeProp('checked');
        $('#inputValue').find('.max-min').hide();
        $('#' + type).modal('show');
    });
    //下拉菜单的增加删除====
    function add(name,desc){
        desc = desc || '候选选项';
        var addstr=document.createElement('div');
        addstr.setAttribute('class','form-group row');
        addstr.innerHTML= "<label  class='col-md-2 col-xs-2 control-label text-right'>选项</label>"+
        "<div class='col-md-5 col-xs-5 md-input'>"+
        "<input type='text' class='form-control'/>"+
        "</div>"+
        "<div class='col-md-5 col-xs-5 text-describe' >"+
        desc + " <span class='delete-node'>删除该项</span>"+
        "</div>";
        $(name).append(addstr)
    }
    $('body').on('click','.delete-node',function(){
        var parent=$(this).parents().eq(1);
        parent.remove();
    });
    $('#inputDropdown .add-option').click(function(){
        add('#dropMenu');
    });
    //单选中的增加============
    $('#inputRadio .add-option').click(function(){
       add('#radioMenu')
    });
    //多选的增加==============
    $('#inputMultiselect .add-option').click(function(){
        add('#MultiselectMenu')
    });
    //滑块增加================
    $('#inputSlider .add-option').click(function(){
        add('#sliderMenu')
    });
    //tr点击事件===============
    $('#addInput tr').click(function(){
       $(this).find('.radio_check').click()
    });
    $('.radio_check').click(function(e){
        e.stopPropagation();
    });
    //数值中是否开启滑块=======
    $('#inputValue .togglebutton input').on('change',function(){
        if($(this).prop('checked')){
            $('.max-min').css('display','block');
        }else{
            $('.max-min').css('display','none');
        }
    })
};
//渲染input输入项
var createInputItem = function (formItem,replaceIndex) {
    var inputTitle = formItem.name;
    var typeText = '';
    var dataType ='';
    if(formItem.inputtype == 5 && formItem.type == 0){
        typeText = '文本';
        dataType = 'inputText';
    }else if(formItem.inputtype == 2 && formItem.type == 0){
        typeText = '日期';
        dataType = 'inputDate';
    }else if(formItem.inputtype == 7 && formItem.type ==0){
        typeText = '图片';
        dataType = 'inputImg';
    }else if(formItem.inputtype == 6 && formItem.type ==0){
        typeText = '视频';
        dataType = 'inputVideo';
    }else if(formItem.inputtype == 5 && formItem.type ==1){
        typeText = '长文本';
        dataType = 'inputLongText';
    }else if(formItem.inputtype == 3 && formItem.type ==1){
        typeText = '下拉菜单';
        dataType = 'inputDropdown';
    }else if(formItem.inputtype == 3 && formItem.type ==0){
        typeText = '单选';
        dataType = 'inputRadio';
    }else if(formItem.inputtype == 4 && formItem.type ==0){
        typeText = '多选';
        dataType = 'inputMultiselect';
    }else if(formItem.inputtype == 8 && formItem.type ==0){
        typeText = '滑块';
        dataType = 'inputSlider';
    }else if(formItem.inputtype == 1 && formItem.type ==0){
        typeText = '数值';
        dataType = 'inputValue';
    }
    var html=[
        "<tr data-json='"+ encodeURI(JSON.stringify(formItem)) +"'>",
        '<td><i class="material-icons move-icon ui-sortable-handle"></i></td>',
        '<td>'+ inputTitle +'</td>',
        '<td>'+ typeText +'</td>',
        '<td><a href="javascript:;" title="编辑" data-type="'+ dataType +'" class="edit"><i class="material-icons"></i></a><a href="javascript:;" class="delete" title="删除"><i class="delete-icon"></i></a></td>',
        '</tr>'
    ].join('');
    if(replaceIndex > -1){
        $('#inputList tr').eq(replaceIndex).after(html);
        $('#inputList tr').eq(replaceIndex).remove();
    }else{
        $('#inputList').append(html);
    }
};
$('.main-btn').click(function () {
    $('#addInput').modal('show');
});
var kindEditorInit = function (cb) {
    KindEditor.ready(function(K) {
        window.editor = K.create('#inputDescription', {
            filterMode : false,
            resizeType : 0,
            height: '350px',
            width : '98%',
            items : ['undo', 'redo','justifyleft', 'justifycenter', 'justifyright','justifyfull', 'insertorderedlist', 'insertunorderedlist', 'subscript',
                'superscript', 'quickformat','formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat','table', 'hr', '|', 'image','media', 'link']
        });
        cb();
    });
};
//表单预览
var formPreview = function () {
    $('#preview').click(function () {
        $(this).attr('href','javascript:;');
        if($(this).attr('data-click') == 'true') return false;
        $(this).attr('data-click','true');
        var inputArray = [];
        $('#inputList tr').each(function () {
            inputArray.push(decodeURI($(this).attr('data-json')));
        });
        localStorage.previewFormJson = inputArray.join('*-*');
        localStorage.previewFormDes = encodeURI(editor.html());
        $(this).attr('data-click','false');
        $(this).attr('href','./form-preview.html');
    });
};
//获取表单预设数据
var getTempNodeForm = function () {
    if(urlParamObj.templateid){
        $('#returnBase').attr('href','./edit-base.html?templateid='+urlParamObj.templateid);
        $('#returnNode').attr('href','./edit-node.html?templateid='+urlParamObj.templateid);
    }
    if(urlParamObj.formid){
        new followupPlan().getTempNodeForm(urlParamObj.formid,function (res, status) {
            res = JSON.parse(res);
            if(res.code = '000'){
                var data = JSON.parse(res.data);
                $('#inputName').val(data.title);
                var writeStaus,readStatus;
                if(data.owner == 2){
                    writeStaus = 0;
                    readStatus = 0;
                }else if(data.owner == 1){
                    writeStaus = 1;
                    readStatus = 0;
                }else if(data.owner == 3){
                    writeStaus = 1;
                    readStatus = 1;
                }else{
                    writeStaus = 0;
                    readStatus = 1;
                }
                $('#inputWrite').val(writeStaus);
                $('#inputRead').val(readStatus);
                editor.html(decodeURI(data.desc));
                var inputList = data.inputs;
                if(inputList){
                    for(var i=0,len=inputList.length;i<len;i++){
                        createInputItem(inputList[i]);
                    }
                }
            }
            $('.outer').addClass('active');
        })
    }else{
        $('.outer').addClass('active');
    }
};
//保存表单预设数据
var setTempNodeForm = function () {
    var setTempNodeFromAjax = function (newone) {
        var formModel={};
        //保存量表名称
        formModel.title= $('#inputName').val().trim();
        if(!formModel.title){
            $$.modal.tips('请输入量表名称',1500);
            return false;
        }
        //保存量表id
        formModel.id = urlParamObj.formid;
        //保存读写权限
        var writeStaus = $('#inputWrite').val();
        var readStatus = $('#inputRead').val();
        if(writeStaus == 0 && readStatus == 0){   //患者填写，都可读
            formModel.owner = 2;
        }else if(writeStaus == 1 && readStatus == 0){ //医生填写，都可读
            formModel.owner = 1;
        }else if(writeStaus == 1 && readStatus == 1){ //医生填写，医生可读
            formModel.owner = 3;
        }else{  //其它
            formModel.owner = 0;
        }
        //保存量表描述
        formModel.desc = encodeURI(editor.html());
        //保存输入项
        formModel.inputs =[];
        var inputList = $('#inputList tr');
        for(var i = 0,len = inputList.length;i<len;i++){
            formModel.inputs.push(JSON.parse(decodeURI($(inputList[i]).attr('data-json'))));
        }
        if(!urlParamObj.stepid){
            $$.modal.tips('保存失败，请重新打开页面',2000);
            return false;
        }
        new followupPlan().setTempNodeForm(urlParamObj.stepid,newone,formModel,function (res, status) {
            res = JSON.parse(res);
            if(res.code = '000'){
                $$.modal.tips('保存成功');
                setTimeout(function () {
                    history.go(-1);
                },500);
            }
        });
    };
    $('#submitForm').click(function () {
        if(urlParamObj.formid){
            //同步
            $$.modal.confirm('修改的内容将在引用该量表的地方生效（所有节点）。如果您只想对单一的量表（本节点）生效，请选择“新量表”，否则请选择“保存”。','新量表','保存',function () {
                setTempNodeFromAjax(0);
            });
            //不同步
            $('#confirmModal').on('click','.cancel',function () {
                setTempNodeFromAjax(1);
            });
        }else{
            //新建
            setTempNodeFromAjax(1);
        }

    });
};
//离开页面提示
var leavePageAlert = function () {
    //关闭页面、刷新页面
    var tempFunction =  function(event) {event.returnValue = '';};
    window.addEventListener("beforeunload",tempFunction);
    //监听a标签
    $('body').on('click','a',function (e) {
        if($(this).attr('id') == 'submitForm'){
            window.removeEventListener("beforeunload",tempFunction);
            return false;
        }
        var href = $(this).attr('href');
        if(($(this).attr('id') != 'preview') && (href.indexOf('#') != 0) && (href != 'javascript:;') && (href != 'javascript:void(0);') && (href != 'javascript:void(0)')){
            e.preventDefault();
            $$.modal.confirm('你即将离开页面，请确保数据已保存','取消','确定',function () {
                window.removeEventListener("beforeunload",tempFunction);
                location.href = href;
            });
        }else{
            window.removeEventListener("beforeunload",tempFunction);
            setTimeout(function () {
                window.addEventListener("beforeunload",tempFunction);
            },500);
        }
    })
};
$(function () {
    kindEditorInit(function () {
        getTempNodeForm();
    });
    calcFormHeight();
    setTempNodeForm();
    $(window).resize(function () {
        calcFormHeight();
    });
    adjustSort();
    inputOperate();
    addInput();
    formPreview();
    leavePageAlert();
});